﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Forms;
using System.IO;
using System.IO.Compression;
using System.Drawing;
using System.Threading;
using System.ComponentModel;

namespace BingImages
{
    class Extract
    {
        private themeForm _themeForm;
        private ProgressBar _pbPicture;
        private Folder _folder;

        public Extract(themeForm themeForm)
        {
            this._themeForm = themeForm;
            this._pbPicture = this._themeForm.getPbPicture();
            this._folder = new Folder();
        }

        public void setExtract(string archiveName, string monthNumber)
        {
            FileInfo[] pngFiles = null;
            string tempDirectoryPath = "";

            pngFiles = this._folder.getFiles("temp", "*-" + monthNumber + "-*.png");

            if (pngFiles.Length == 0)
            {
                string contentPath = "";
                FileInfo contentFile = null;

                tempDirectoryPath = this._folder.tempPath;

                ZipFile.ExtractToDirectory(archiveName, tempDirectoryPath);

                contentPath = tempDirectoryPath + @"\[Content_Types].xml";
                contentFile = new FileInfo(contentPath);
                contentFile.Delete();

                pngFiles = this._folder.getFiles("temp", "*-" + monthNumber + "-*.png");

                this._pbPicture.Maximum = pngFiles.Count();
                this._pbPicture.Visible = true;

                foreach (FileInfo file in pngFiles)
                {
                    this.newFile(file, tempDirectoryPath);
                }
            }
        }

        private void newFile(FileInfo file, string tempDirectoryPath)
        {
            FileStream fs = null;
            Image streamPicture = null;
            Image clonePicture = null;
            Image picture = null;

            using (fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                streamPicture = Image.FromStream(fs);
                fs.Close();
                clonePicture = streamPicture.Clone() as Image;
                streamPicture.Dispose();
                picture = clonePicture;
                picture = (Image)(new Bitmap(picture, 131, 121));
                picture.Save(tempDirectoryPath + "\\" + Path.GetFileNameWithoutExtension(file.Name) + ".jpg");
            }

            this._pbPicture.Value += 1;
        }
    }
}
